import Vue from 'vue'
import { getComputedHeight } from '@web-utils/core'

async function adjustNode(el, binding) {
  await Vue.nextTick()
  const span = el.querySelector('.section-title')
  const parentHeight = getComputedHeight(el)
  if (span) {
    if (binding.arg === 1) {
      span.style.height = `${parentHeight - 1}px`
      span.style.lineHeight = `${parentHeight - 1}px`
      span.classList.add('line-height-1px')
    } else {
      span.style.height = `${parentHeight - 2}px`
      span.style.lineHeight = `${parentHeight - 2}px`
      span.classList.remove('line-height-1px')
    }
  }
}

export default {
  async bind(el, binding) {
    const span = document.createElement('span')
    span.classList.add('section-title')
    span.innerText = binding.value
    el.prepend(span)
    await adjustNode(el, binding)
  },
  inserted: (el, binding) => adjustNode(el, binding),
  update: (el, binding) => adjustNode(el, binding),
  componentUpdated: (el, binding) => adjustNode(el, binding),
  unbind(el) {
    const span = el.querySelector('.section-title')
    span?.remove()
  }
}
